/*
 *  Class name: AddressBookManagerImpl.java
 *  Version: 1.0
 *  Date: 4.6.2014
 */
package cz.muni.fi.pv168.addressbook.daos.impl;

import cz.muni.fi.pv168.addressbook.daos.AddressBookManager;
import cz.muni.fi.pv168.addressbook.daos.ContactManager;
import cz.muni.fi.pv168.addressbook.daos.PersonManager;
import cz.muni.fi.pv168.addressbook.entities.Contact;
import cz.muni.fi.pv168.addressbook.entities.Person;
import cz.muni.fi.pv168.addressbook.entities.validators.Validator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author Michal Ďuriš
 */
public class AddressBookManagerImpl implements AddressBookManager {

    private final PersonManager personManager;
    private final ContactManager contactManager;

    public AddressBookManagerImpl(PersonManager personManager,
                                  ContactManager contactManager) {
        this.personManager = personManager;
        this.contactManager = contactManager;
    }

    @Override
    public List<Contact> getAllContactsOfPerson(Person person) {

        List<Contact> personContacts = contactManager.getAllContacts()
                .stream()
                .filter(contact -> contact.getPerson().getId().equals(person
                                .getId()))
                .collect(Collectors.toCollection(ArrayList::new));

        return Validator.NOT_EMPTY_LIST_PREDICATE.test(personContacts) ? personContacts : Collections
                .emptyList();
    }

    @Override
    public List<Person> findContact(String searchString) {

        List<Person> searchResult = contactManager.getAllContacts()
                .stream()
                .filter(contact -> contact.getContactValue().toLowerCase()
                        .startsWith(searchString.toLowerCase()))
                .map(contact -> personManager.getPersonById(contact
                                .getPersonID()))
                .distinct()
                .collect(Collectors.toCollection(ArrayList::new));

        return Validator.NOT_EMPTY_LIST_PREDICATE.test(searchResult) ? searchResult : Collections
                .emptyList();
    }

}
